package validate

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gvalid"
)

// RulePGCoinOrderExistsById 验证盘古币订单是否存在
func RulePGCoinOrderExistsById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 检测订单是否存在
	if b, _ := service.PgCoin().OrderModel().Exists(ctx, g.Map{
		dao.PanguCoinOrder.Columns().Id: in.Value.Uint(),
	}); !b {
		return exception.New(`盘古币充值订单不存在`)
	}
	return nil
}

// RulePGCoinUserOrderExistsById 检测用户订单是否存在
func RulePGCoinUserOrderExistsById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 检测用户订单是否存在
	if b, _ := service.PgCoin().OrderModel().Exists(ctx, g.Map{
		dao.PanguCoinOrder.Columns().Uid: service.BizCtx().GetUid(ctx),
		dao.PanguCoinOrder.Columns().Id:  in.Value.Uint(),
	}); !b {
		return exception.New(`用户充值订单不存在`)
	}
	return nil
}

// RulePGCoinUserValid 验证用户充值订单有效性
func RulePGCoinUserValid(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 检测订单是否有效
	detail, err := service.PgCoin().GetOrderDetail(ctx, in.Value.Uint(), enums.FormSideBus)
	if err != nil {
		return err
	}
	// 订单是否已支付
	if detail.PayStatus == enums.PGCoinOrderPayPaid {
		return exception.Newf(`订单%s`, detail.PayStatus.Fmt())
	}
	// 订单状态
	if detail.Status != enums.PGCoinOrderStatusPending {
		return exception.Newf(`订单%s`, detail.Status.Fmt())
	}
	return nil
}
